package de.se.ludoapp.activity.task;

import android.content.Intent;
import android.os.AsyncTask;
import android.widget.Toast;
import de.se.ludoapp.LudoApplication;
import de.se.ludoapp.activity.GameActivity;
import de.se.ludoapp.activity.NewGameActivity;
import de.se.ludoapp.activity.PlayerTableActivity;
import de.se.ludoapp.gaming.Game;
import de.se.ludoapp.response.GameFieldResponse;

/**
 * Task to ask if the game is started on the server.
 * 
 * @author Marlen Rotert
 * 
 */
public class IsGameStartedTask extends AsyncTask<String, Integer, String> {

	private LudoApplication ludoApp;
	private NewGameActivity context;
	private boolean isGameStarted;
	private boolean isTableClosed;

	public IsGameStartedTask(LudoApplication ludoApp, NewGameActivity context) {
		super();
		this.ludoApp = ludoApp;
		this.context = context;
		this.isGameStarted = false;
		this.isTableClosed = false;
	}

	/**
	 * Destroy Game on Server.<br>
	 * This method is executed in a concurrent thread (asynchronous). Therefore
	 * you mustn't accessed on view elements!
	 */
	@Override
	protected String doInBackground(String... params) {
		/* Execute is game started */
		GameFieldResponse gameFieldResponse = ludoApp.getLudoStub()
				.isTheGameStarted(ludoApp.getlogedinUser().getSessionId(),
						ludoApp.getCurrentGame().getGameId());

		Game game = ludoApp.getCurrentGame();
		game.setGameField(gameFieldResponse.getGameField());
		game.setUpNext(gameFieldResponse.getUpNext());

		if (gameFieldResponse.getReturnCode() == 0) {
			this.isGameStarted = true;

		}
		if (gameFieldResponse.getReturnCode() == 30) {
			this.isTableClosed = true;
		}
		return gameFieldResponse.getMsg();
	}

	/**
	 * Back to last Activity and the user has no current game <br>
	 * This method is invoked when the OpenGameTask is executed. You are only
	 * allowed here to access on view Elements (TextView and Buttons)!
	 */
	@Override
	protected void onPostExecute(String result) {
		if (this.isGameStarted) {
			Toast.makeText(context, "Das Spiel wurde gestartet",
					Toast.LENGTH_LONG).show();
			Intent intentGame = new Intent(context, GameActivity.class);
			context.startActivity(intentGame);
			context.finish();
		}
		if (this.isTableClosed) {
			Toast.makeText(context, result, Toast.LENGTH_LONG).show();
			Intent intentGame = new Intent(context, PlayerTableActivity.class);
			context.startActivity(intentGame);
			context.finish();
		}
	}
}
